package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.LoginDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserLoginService;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    private ApUserMapper apUserMapper;

    private static final String TOKEN = "token";


    @Override
    public ResponseResult login(LoginDto dto) {
        // 1.参数校验
        if (dto.getEquipmentId() == null
                && (StringUtils.isEmpty(dto.getPhone()) || StringUtils.isEmpty(dto.getPassword()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Map<String, String> resultMap = new HashMap<>();
        if (StringUtils.isNotEmpty(dto.getPhone()) && StringUtils.isNotEmpty(dto.getPassword())) {
            // 2.手机号和密码登录
            ApUser dbApUser =
                    apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (dbApUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在！");
            }
            String psdw =
                    DigestUtils.md5DigestAsHex((dto.getPassword() + dbApUser.getSalt()).getBytes());
            if (!psdw.equals(dbApUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            String token = AppJwtUtil.getToken(dbApUser.getId().longValue());
            resultMap.put(TOKEN, token);
        } else{
            // 3.设备登录
            String token = AppJwtUtil.getToken(0L);
            resultMap.put(TOKEN, token);
        }
        return ResponseResult.okResult(resultMap);
    }

    public static void main(String[] args) {
        String salt = "abc";

        String s = DigestUtils.md5DigestAsHex(("123456" + salt).getBytes());
        System.out.println(s);
    }
}
